<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
      ></el-alert>
      <!-- 选择分类 -->
      <el-row>
        <el-col
          >选择商品分类：
          <el-cascader
            v-model="goodsCateVal"
            :options="goodsCateList"
            :props="props"
            @change="cascaderChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 参数列表 -->
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <!-- 静态参数列表 -->
        <el-tab-pane label="静态参数" name="only">
          <!-- 添加静态参数按钮 -->
          <el-button type="primary" size="mini" @click="addGoodsParamsBtn"
            >添加参数</el-button
          >
          <!-- 静态列表 -->
          <el-table
            :data="goodsCateParams"
            style="width: 100%"
            stripe
            border
            :empty-text="isTipsNull"
          >
            <!-- 参数详情标签 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="item in scope.row.attr_vals"
                  v-bind:key="item.attr_id"
                  closable
                  hit
                  @close="handleClose(item, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editGoodsParams(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delGoodsParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 动态参数列表 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" @click="addGoodsParamsBtn"
            >添加参数</el-button
          >
          <!-- 动态列表 -->
          <el-table
            :data="goodsCateParams"
            style="width: 100%"
            stripe
            border
            :empty-text="isTipsNull"
          >
            <el-table-column type="expand">
              <!-- 参数详情标签 -->
              <template slot-scope="scope">
                <el-tag
                  v-for="item in scope.row.attr_vals"
                  v-bind:key="item.attr_id"
                  closable
                  hit
                  @close="handleClose(item, scope.row)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editGoodsParams(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="delGoodsParams(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加分类 -->
    <el-dialog
      @close="cloaddGoodsParams"
      :title="'添加' + isActiveName"
      :visible.sync="addGoodsParamsdialog"
      width="50%"
    >
      <el-form
        ref="addGoodsParamsRef"
        :model="addGoodsParams"
        label-width="100px"
        :rules="addGoodsParamsRules"
      >
        <el-form-item :label="isActiveName + ':'" prop="attr_name">
          <el-input v-model="addGoodsParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addGoodsParamsdialog = false">取 消</el-button>
        <el-button type="primary" @click="subaddGoodsParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改分类 -->
    <el-dialog
      :title="'修改' + isActiveName"
      :visible.sync="modGoodsParamsdialog"
      width="50%"
    >
      <el-form
        ref="modGoodsParamsRef"
        :model="modGoodsParams"
        label-width="100px"
        :rules="modGoodsParamsRules"
      >
        <el-form-item :label="isActiveName + ':'" prop="attr_name">
          <el-input v-model="modGoodsParams.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modGoodsParamsdialog = false">取 消</el-button>
        <el-button type="primary" @click="subModGoodsParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //  商品分类列表
      goodsCateList: [],
      // 级联选择配置
      props: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器选中值
      goodsCateVal: [],
      // 标签页选中页的name
      activeName: 'only',
      // 商品参数
      goodsCateParams: [],
      // 是否显示添加分类参数对话框
      addGoodsParamsdialog: false,
      // 添加商品分类参数的参数
      addGoodsParams: {
        attr_name: '',
        attr_sel: ''
      },
      // 添加商品分类参数验证规则
      addGoodsParamsRules: {
        attr_name: [
          { required: true, message: '请输入分类参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 是否显示修改分类参数对话框
      modGoodsParamsdialog: false,
      // 修改商品分类参数的参数
      modGoodsParams: {
        attr_name: '',
        attr_sel: ''
      },
      // 添加商品分类参数验证规则
      modGoodsParamsRules: {
        attr_name: [
          { required: true, message: '请输入分类参数名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 商品分类参数id
      attrId: 0
    }
  },
  created() {
    this.getGoodsCateList()
  },
  methods: {
    //  获取商品分类列表
    async getGoodsCateList() {
      const { data } = await this.$http.get('categories')
      if (data.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      // this.$message.success('获取商品分类列表成功')
      console.log('获取商品分类列表成功')
      console.log(data)
      this.goodsCateList = data.data
    },
    //  级联选择器发生改变
    async cascaderChange() {
      console.log(this.goodsCateVal[2])
      const {
        data
      } = await this.$http.get(
        `categories/${this.goodsCateVal[2]}/attributes/`,
        { params: { sel: this.activeName } }
      )
      if (data.meta.status !== 200) {
        this.goodsCateParams = []
        return this.$message.error('根据id查找分类参数失败')
      }
      // this.$message.success("根据id查找分类参数成功")
      console.log('根据id查找分类参数成功')
      // 处理分类参数中参数详情
      data.data.forEach(item => {
        // 是否切换参数详情标签 设置为当前项自定义属性
        item.inputVisible = false
        // 参数详情标签的值
        item.inputValue = ''
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
      })
      this.goodsCateParams = data.data
      console.log('根据id查找分类参数:')
      console.log(this.goodsCateParams)
    },
    //  当tags发生改变,查询是静态还是动态
    tabClick() {
      this.cascaderChange()
    },
    //  添加分类参数按钮
    addGoodsParamsBtn() {
      this.addGoodsParamsdialog = true
    },
    //  关闭对话框
    cloaddGoodsParams() {
      this.$refs.addGoodsParamsRef.resetFields()
    },
    //  提交添加表单
    subaddGoodsParams() {
      this.addGoodsParams.attr_sel = this.activeName
      this.$refs.addGoodsParamsRef.validate(async valid => {
        if (!valid) return false
        const { data } = await this.$http.post(
          `categories/${this.goodsCateVal[2]}/attributes`,
          this.addGoodsParams
        )
        console.log(data)
        if (data.meta.status !== 201) {
          this.addGoodsCatedialog = false
          return this.$message({ message: '添加分类参数失败', type: 'error' })
        }
        this.$message({ message: '添加分类参数成功', type: 'success' })
        this.addGoodsParamsdialog = false
        this.cascaderChange()
      })
    },
    //  提交修改表单
    subModGoodsParams() {
      this.modGoodsParams.attr_sel = this.activeName
      this.$refs.modGoodsParamsRef.validate(async valid => {
        if (!valid) return false
        const { data } = await this.$http.put(
          `categories/${this.goodsCateVal[2]}/attributes/${this.attrId}`,
          this.modGoodsParams
        )
        console.log(data)
        if (data.meta.status !== 200) {
          this.addGoodsCatedialog = false
          return this.$message({ message: '更新分类参数失败', type: 'error' })
        }
        this.$message({ message: '更新分类参数成功', type: 'success' })
        this.modGoodsParamsdialog = false
        this.cascaderChange()
      })
    },
    //  修改分类参数按钮
    async editGoodsParams(row) {
      const {
        data
      } = await this.$http.get(
        `categories/${this.goodsCateVal[2]}/attributes/${row.attr_id}`,
        { params: { attr_sel: this.activeName } }
      )
      if (data.meta.status !== 200) {
        return this.$message.error(`分类参数 ${row.attr_name} 查询失败`)
      }
      // this.$message.success(`分类参数 ${row.attr_name} 查询成功`)
      console.log(`分类参数 ${row.attr_name} 查询成功`)
      console.log(data)
      this.modGoodsParams.attr_name = data.data.attr_name
      this.modGoodsParams.attr_sel = data.data.attr_sel
      this.attrId = data.data.attr_id
      this.modGoodsParamsdialog = true
    },
    //  删除分类参数按钮
    async delGoodsParams(row) {
      this.$confirm(`是否删除 ${row.attr_name} 分类参数?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data } = await this.$http.delete(
            `categories/${this.goodsCateVal[2]}/attributes/${row.attr_id}`
          )
          console.log(data)
          if (data.meta.status !== 200) {
            return this.$message({
              type: 'error',
              message: ` 分类参数 ${row.attr_name} 删除失败`
            })
          }
          this.$message({
            type: 'success',
            message: `分类参数 ${row.attr_name} 删除成功`
          })
          this.cascaderChange()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击参数详情标签
    showInput(row) {
      row.inputVisible = true
      /***
       *  $nextTick作用：当页面元素被重新渲染后，才会执行其中回调
       *  在点击标签时，不会立即出现输入框，而是从新渲染后，再获取焦点
       *  如果直接获取焦点，还没有输入框
       ***/

      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 生成新的参数标签
    async handleInputConfirm(row) {
      if (row.inputValue.trim()) {
        row.attr_vals.push(row.inputValue)
      }
      const { data } = await this.$http.put(
        `categories/${this.goodsCateVal[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (data.meta.status !== 200) {
        return this.$message.error('添加分类参数标签失败！')
      }
      this.$message.success('添加分类参数标签成功！')

      console.log(data)
      row.inputVisible = false
      row.inputValue = ''
    },
    // 关闭参数标签
    async handleClose(item, row) {
      row.attr_vals.splice(row.attr_vals.indexOf(item), 1)
      const { data } = await this.$http.put(
        `categories/${this.goodsCateVal[2]}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (data.meta.status !== 200) {
        return this.$message.error('删除分类参数标签失败！')
      }
      this.$message.success('删除分类参数标签成功！')
    }
  },
  computed: {
    //   添加参数标题处理
    isActiveName: function() {
      return this.activeName === 'many' ? '动态参数' : '静态参数'
    },
    isTipsNull: function() {
      return this.goodsCateVal.length === 0 ? '请选择商品分类' : '暂无参数'
    }
  }
}
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin-top: 10px;
  margin-left: 10px;
}
.el-tag + .el-tag {
  margin-right: 10px;
}
.button-new-tag {
  margin-top: 10px;
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
